package com.example.teacherservice.controller;

import com.example.teacherservice.dto.*;
import com.example.teacherservice.entity.Chapter;
import com.example.teacherservice.entity.Course;
import com.example.teacherservice.service.ChapterService;
import com.example.teacherservice.service.FileStorageService;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/spoc/vod/chapter")
public class ChapterController {
    private final ChapterService chapterService;
    private final FileStorageService fileStorageService;

    public ChapterController(ChapterService chapterService, FileStorageService fileStorageService) {
        this.chapterService = chapterService;
        this.fileStorageService = fileStorageService;
    }

    @PostMapping("/save")
    public ResponseEntity<ApiResponse> saveChapter(@RequestBody Chapter chapter) {
        Chapter savedChapter = chapterService.saveChapter(chapter);
        return ResponseEntity.ok(new ApiResponse(true, "章节保存成功", savedChapter));
    }

    @PostMapping("/update")
    public ResponseEntity<ApiResponse> updateChapter(@RequestBody Chapter chapter) {
        Chapter updatedChapter = chapterService.updateChapter(chapter);
        return ResponseEntity.ok(new ApiResponse(true, "章节更新成功", updatedChapter));
    }

    @DeleteMapping("/remove/{id}")
    public ResponseEntity<ApiResponse> deleteChapter(@PathVariable Long id) {
        chapterService.deleteChapter(id);
        return ResponseEntity.ok(new ApiResponse(true, "章节删除成功"));
    }

    @GetMapping("/get/{id}")
    public ResponseEntity<ApiResponse> getChapterInfo(@PathVariable Long id) {
        Chapter chapter = chapterService.getChapterInfo(id);
        return ResponseEntity.ok(new ApiResponse(true, "获取章节信息成功", chapter));
    }

    @GetMapping("/getNestedTreeListByTeacher/{courseId}")
    public ResponseEntity<ApiResponse> getNestedTreeListByTeacher(@PathVariable Long courseId) {
        List<Chapter> chapters = chapterService.getNestedTreeListByTeacher(courseId);
        return ResponseEntity.ok(new ApiResponse(true, "获取章节列表成功", chapters));
    }

    @PostMapping("/updateIndex")
    public ResponseEntity<ApiResponse> updateChapterIndex(@RequestParam Long courseId,
                                                          @RequestParam Integer oldIndex,
                                                          @RequestParam Integer newIndex) {
        chapterService.updateChapterIndex(courseId, oldIndex, newIndex);
        return ResponseEntity.ok(new ApiResponse(true, "章节顺序更新成功"));
    }

//    @PostMapping
//    public ResponseEntity<ApiResponse> createChapter(
//            @RequestBody ChapterCreateRequest request) {
//        ChapterDTO chapter = chapterService.createChapter(request);
//        return ResponseEntity.ok(new ApiResponse(true, "章节创建成功", chapter));
//    }

    @PutMapping("/{chapterId}")
    public ResponseEntity<ApiResponse> updateChapter(
            @PathVariable Long chapterId,
            @RequestBody ChapterUpdateRequest request) {
        ChapterDTO chapter = chapterService.updateChapter(chapterId, request);
        return ResponseEntity.ok(new ApiResponse(true, "章节更新成功", chapter));
    }

    @DeleteMapping("/{chapterId}")
    public ResponseEntity<ApiResponse> deleteChapter1(
            @PathVariable Long chapterId) {
        chapterService.deleteChapter(chapterId);
        return ResponseEntity.ok(new ApiResponse(true, "章节删除成功"));
    }

    @PutMapping("/order")
    public ResponseEntity<ApiResponse> updateChapterOrder(
            @RequestBody ChapterOrderUpdateRequest request) {
        chapterService.updateChapterOrder(request);
        return ResponseEntity.ok(new ApiResponse(true, "章节顺序更新成功"));
    }

    // ChapterController.java 新增批量创建接口
    // ChapterController.java
    @GetMapping("/video-info/{courseId}/{chapterId}")
    public ResponseEntity<ApiResponse> getVideoInfo(
            @PathVariable Long courseId,
            @PathVariable Long chapterId) {

        ChapterVideoInfoDTO videoInfo = chapterService.getVideoInfo(courseId, chapterId);
        return ResponseEntity.ok(new ApiResponse(true, "获取视频信息成功", videoInfo));

    }


    /**
     * 上传视频文件并创建章节（替代原createChapter方法）
     */
    @PostMapping("/upload")
    public ResponseEntity<ApiResponse> uploadChapterVideo(
            @RequestParam("file") MultipartFile file,
            @RequestParam("courseId") Long courseId,
            @RequestParam("chapterTitle") String chapterTitle,
            @RequestParam(value = "chaIndex", required = false) Integer chaIndex) {

        try {
            // 1. 处理视频上传和解析
            String videoUrl = fileStorageService.handleVideoUpload(file, courseId);

            // 2. 获取视频时长
            long duration = fileStorageService.parseVideoDuration(videoUrl);

            // 3. 创建章节记录
            ChapterCreateRequest request = new ChapterCreateRequest();
            request.setCourseId(courseId);
            request.setTitle(chapterTitle);
            request.setUrl(videoUrl);
            request.setIndex(chaIndex);
            request.setDuration(duration); // 设置视频时长

            ChapterDTO chapter = chapterService.createChapter(request);
            return ResponseEntity.ok(new ApiResponse(true, "视频章节创建成功", chapter));

        } catch (Exception e) {
            return ResponseEntity.status(500)
                    .body(new ApiResponse(false, "视频处理失败: " + e.getMessage()));
        }
    }

    /**
     * 更新章节视频（新增方法）
     */
    @PutMapping("/{chapterId}/video")
    public ResponseEntity<ApiResponse> updateChapterVideo(
            @PathVariable Long chapterId,
            @RequestParam("file") MultipartFile file) {

        try {
            // 1. 获取原章节信息
            Chapter chapter = chapterService.getChapterInfo(chapterId);

            // 2. 处理新视频上传
            String newVideoUrl = fileStorageService.handleVideoUpload(file, chapter.getCourseId());

            // 3. 获取新视频时长
            long newDuration = fileStorageService.parseVideoDuration(newVideoUrl);

            // 4. 更新章节视频信息
            ChapterUpdateRequest request = new ChapterUpdateRequest();
            request.setUrl(newVideoUrl);
            request.setDuration(newDuration); // 更新视频时长

            ChapterDTO updatedChapter = chapterService.updateChapter(chapterId, request);
            return ResponseEntity.ok(new ApiResponse(true, "章节视频更新成功", updatedChapter));

        } catch (Exception e) {
            return ResponseEntity.status(500)
                    .body(new ApiResponse(false, "视频更新失败: " + e.getMessage()));
        }
    }


}